package com.sun.communit;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * flag=1  A 打印
 * flag=2  B 打印
 * flag=3  C 打印
 */

public class Communication {

    public static void main(String[] args) {
        ShareSource shareSource = new ShareSource();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                shareSource.printA();
            }
        },"AA").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                shareSource.printB();
            }
        },"BB").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                shareSource.printC();
            }
        },"CC").start();
    }
}


class ShareSource {
   private int flag = 1;
    Lock lock = new ReentrantLock();
    Condition conditionA = lock.newCondition();
    Condition conditionB = lock.newCondition();
    Condition conditionC = lock.newCondition();

    //打印的方法
    public void printA(){
        try {
            lock.lock();
            while(flag !=1){
                //A等待
                conditionA.await();
            }
            //干活 A开始打印
            for (int i = 1; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + "打印了：" + i + "次");
            }
            flag = 2;
            conditionB.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    //打印的方法
    public void printB(){
        try {
            lock.lock();
            while(flag !=2){
                //B等待
                conditionB.await();
            }
            //干活 B开始打印
            for (int i = 1; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + "打印了：" + i + "次");
            }
            flag = 3;
            conditionC.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    //打印的方法
    public void printC(){
        try {
            lock.lock();
            while(flag !=3){
                //C等待
                conditionC.await();
            }
            //干活 C开始打印
            for (int i = 1; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + "打印了：" + i + "次");
            }
            flag = 1;
            conditionA.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
